<?php


namespace App\Biquge;


use App\Core\Ioc;
use App\Utils\Cache;
use App\Worker\Worker;

class NovalStarter
{

    protected $max_i = 5;
    protected $max_j = 5;

    protected $url = 'http://www.biqukan.com';
    protected $topic;

    public function __construct()
    {
        $this->topic = new CrawlUrlTopic();
    }

    public function start(Ioc $ioc)
    {
        $jobs = [];
        $old_i = Cache::get('MAX_I') ?? 0;
        $start_i = ($this->max_i - $old_i) > 0 ? $old_i : $this->max_i;

        $old_j = Cache::get('MAX_J') ?? 1;
        $start_j = ($this->max_j - $old_j) > 0 ? $old_j : $this->max_j;
        for ($i = $start_i; $i < $this->max_i; $i++) {
            for ($j = $start_j; $j < $this->max_j + 1; $j++) {
                $jobs[] = json_encode([
                    'job' => serialize(new NovalJob(sprintf('%s/%s_%s', $this->url, $i, ($i == 0 ? '' : $i) . $j))),
                    'attempts' => 1
                ]);
            }
        }
        Cache::set('MAX_I', $this->max_i);
        Cache::set('MAX_J', $this->max_j);
        if ($jobs) {
            Cache::rpush($this->topic->name, $jobs);
        }
        (new Worker($ioc, $this->topic))->start();
    }

}